//
//  DanmuSocket.swift
//  danmuDemo
//
//  Created by BigL055 on 16/6/14.
//  Copyright © 2016年 bigL.MoreDemo.com. All rights reserved.
//

import UIKit
import CocoaAsyncSocket

class BLDanmuSocket: BLDouyuTVSocket {
    
    static let sharedInstance = BLDanmuSocket()
    
    var isFirstDate : Bool?
    
    
    override func setServerConfig() {
        
        let ip = "danmu.douyutv.com"
        let sevArray : [[String : String]] = [["ip" : ip , "port" : "12061"],
                                              ["ip" : ip , "port" : "12062"],
                                              ["ip" : ip , "port" : "8601"],
                                              ["ip" : ip , "port" : "8602"]]
        server = [BLServerModel]()
        
        for sevCfg : [String : String] in sevArray{
            let model : BLServerModel = BLServerModel()
            model.ip = sevCfg["ip"]
            model.port = UInt16(sevCfg["port"]!)
            server.append(model)
        }
    }
    
    
    
    override func connectSocketHost() {
        
        socket = AsyncSocket(delegate: self)
        let ip = "danmu.douyutv.com"
        let port : UInt16 = 8602
        do{
            try socket?.connectToHost(ip, onPort: port, withTimeout: 30)
        }catch{
            print(error)
        }
    }
    
    /// 心跳包
    override func longConnectToSocket() {
        //keep live 所发送的信息
        /*
         心跳包内容
         type@=mrkl/
         */
        
        let keepLive = "type@=keeplive/tick@=\(String.getTimeSince())/"
        let postKLData : NSData = packToData(keepLive)
        socket?.writeData(postKLData, withTimeout: 30, tag: 1)
        
    }
}

extension BLDanmuSocket{
    

    
    override func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
        
        print("---弹幕服务器连接成功---")
        
        /*
         游客登陆信息
         type@=loginreq/username@=visitor13227520/password@=1234567890123456/roomid@=213116/
         username:
         roomid:
         加入弹幕组
         type@=joingroup/rid@=213116/gid@=1/
         */
        
        let danmuLogin : String = "type@=loginreq/username@=\(vistorID)/password@=1234567890123456/roomid@=\(room)/"
        let postLoginData : NSData = packToData(danmuLogin)
        isFirstDate = true
        socket?.writeData(postLoginData, withTimeout: 30, tag: 1)
    }
    
    ///断开链接
    override func onSocketDidDisconnect(sock: AsyncSocket!) {
        print("----弹幕服务器断开----")
        let loginOut = "type@=logout/"
        let postKLData : NSData = packToData(loginOut)
        socket?.writeData(postKLData, withTimeout: -1, tag: 1)
    }
    
    func startKLTimer() {
        
        connectTimer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: #selector(longConnectToSocket), userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(connectTimer!, forMode: NSRunLoopCommonModes)

    }
}
